﻿////入口自定义模块
//layui.extend({
//    permisson: '/lib/permisson'
//}).define(['layer', 'permisson', 'element','form'], function (exports) {
//    var layer = layui.layer,
//        element = layui.element,
//        form = layui.form,
//        $=layui.$,
//        permisson = layui.permisson;
//    var index = {
//        loadLayerIndex: 0,
//        handleCallbackResult: function (response, callback) {
//            var rtnResult = response.responseJSON;
//            if (rtnResult) {
//                if (rtnResult.code !== 0) {
//                    layer.alert(rtnResult.msg,
//                        {
//                            icon: 2,
//                            title: '信息提示'
//                        });
//                } else {
//                    callback && callback(rtnResult.data);
//                }
//            }
//        }
//    }

//    //请求开始的时候，开启加载状态
//    window.onBegin = function () {
//        index.loadLayerIndex = layer.load(1,
//            {
//                shade: [0.1, '#000']
//            });
//    }

//    //请求加载完成后，关闭加载
//    window.onSuccess = function () {
//        layer.close(index.loadLayerIndex);
//    }

//    //请求出现错误时，关闭加载层，提示系统错误
//    window.onFailure = function () {
//        layer.closeAll();
//        layer.alert('服务器请求错误，请稍候重试',
//            {
//                icon: 2,
//                title: '错误提示'
//            });
//    }

//    if (layui.cache.module) {
//        //模块名称
//        var moduleName = layui.cache.module.moduleName;

//        //动态设置别名
//        var extentd = {};
//        extentd[moduleName] = 'lib/modules/' + moduleName;
//        //动态加载模块
//        layui.extend(extentd).use(moduleName);
//    }

//    //控制操作权限
//    permisson.controllPermisson();

//    //对外输出接口
//    exports('index', index);
//})


//自定义Layui模块

layui.define(['layer', 'form', 'element', 'upload', 'util'], function (exports) {
    var layer = layui.layer,
        form = layui.form,
        util = layui.util,
        upload = layui.upload,
        element = layui.element,
        $ = layui.$;


    layui.focusInsert = function (obj, str) {
        var result, val = obj.value;
        obj.focus();
        if (document.selection) { //ie
            result = document.selection.createRange();
            document.selection.empty();
            result.text = str;
        } else {
            result = [val.substring(0, obj.selectionStart), str, val.substr(obj.selectionEnd)];
            obj.focus();
            obj.value = result.join('');
        }
    };

    //Ajax开始请求的函数，开启加载层
    window, onBegin = function () {
        layer.load(1,
            {
                shade: [0.1, '#000']
            });
    }

    //Ajax完成后的回调函数，关闭加载层
    window.onSuccess = function () {
        layer.closeAll();
    }

    //Ajax出现错误的回调函数
    window.onFailure = function () {
        //首先关闭加载层
        layer.closeAll();

        //弹出错误提示
        layer.alert('服务器请求错误，请稍后重试',
            {
                icon: 2,
                title: '错误提示'
            });
    }

    var index = {
        handleCallbackResult: function (response, success) {
            var rtnResult = response.responseJSON;
            if (rtnResult) {
                //返回状态码不为零，提示错误
                if (rtnResult.code !== 0) {
                    layer.alert(rtnResult.msg,
                        {
                            icon: 0,
                            title: '信息提示'
                        });
                } else {
                    //执行成功回调函数
                    success && success(rtnResult.data);
                }
            } else {
                return;
            }
        },

        //自定义Ajax访问
        jsonAjax: function (url, data, success, option) {
            //判断第二个参数是否为函数类型
       
            var isFunction = typeof data === 'function';
            //若未传递参数，默认第二个参数为回调函数，参数为空
            if (isFunction) {
                option = success;
                success = data;
                data = {};
            }
            option = option || {};
            return $.ajax({
                type: option.type || 'post',
                dataType: option.dataType || 'json',
                async: option.async || 'true',
                data: data,
                url: url,
                success: function (res) {
                    if (res.code === 0) {
                        success && success(res.data);
                  debugger
                    } else {
                        layer.msg(res.msg || res.code, { shift: 6 });
                        option.error && option.error();
                    }
                },
                error: function (e) {
                    layer.msg('请求异常。请重试！', { shift: 6 });
                    option.error && option.error(e);
                }
            });
        },

        //数据提交前拦截时间
        beforeSubmit: function (filter) {
            form.on('submit(' + filter + ')', function (data) {
                //禁用按钮点击时间
                var $btnElem = $(data.elem);
                $btnElem.prepend(loadElem);
                $btnElem.attr('disabled', true);
                $btnElem.addClass('layui.btn-disabled');

                //按钮设置了disabled后，无法提交表单，主动提交
                var $formElem = $(data.form);
                $formElem.submit();
            });
        },


        ////提交完成后回调
        //afterSubmit: function (response, elemName, callback) {
        //    var $btnElem = $(elemName);
        //    $btnElem.attr('disabled', false);
        //    $btnElem.removeClass('layui-btn-disabled');
        //    $($btnElem.find('i'))[0].remove();

        //    var rtnResult = response.responseJSON;
        //    if (rtnResult !== 0) {
        //        layer.msg(rtnResult.msg, { icon: 5, anim: 6, time: 2000 });
        //    } else {
        //        callback && callback(rtnResult.data);
        //    }
        //},

        layEditor: function (options) {
            var html = [
                '<div class="layui-unselect fly-edit">',
                '<span type="face" title="插入表情"><i class="iconfont icon-yxj-expression" style="top:1px;"></i></span>',
                '<span type="picture" title="插入图片: img[src]"><i class="iconfont icon-tupian"></i></span>',
                '<span type="href" title="超链接格式：a(href)(text)"><i class="iconfont icon-lianjie"></i></span>',
                '<span type="code" title="插入代码或引用"><i class="iconfont icon-emwdaima" style="top:1px;"></i></span>',
                '<span type="hr" title="插入水平线">hr</span>',
                '<span type="yulan" title="预览"><i class="iconfont icon-yulan1"></i></span>', '</div>'
            ].join('');

            var log = {},
                mod = {
                    //插入表情
                    face: function (editor, self) {
                        var str = '', ul, face = index.faces;
                        for (var key in face) {
                            str += '<li title="' + key + '"><img src="' + face[key] + '"></li>';
                        }
                        str = '<ul id="LAY-editface" class="layui-clear">' + str + '</ul>';
                        layer.tips(str,
                            self,
                            {
                                tips: 3,
                                time: 0,
                                skin: 'layui-edit-face'
                            });

                        $(document).on('click',
                            function () {
                                layer.closeAll('tips');
                            });
                        $('#LAY-editface li').on('click',
                            function () {
                                var title = $(this).attr('title') + ' ';
                                layui.focusInsert(editor[0], 'face' + title);
                            });
                    },

                    //插入图片
                    picture: function (editor) {
                        options = options || {};
                        layer.open({
                            type: 1,
                            id: 'fly-jie-upload',
                            title: '插入图片',
                            area: 'auto',
                            shade: false,
                            area: '465px',
                            fixed: false,
                            offset: [
                                editor.offset().top - $(window).scrollTop() + 'px', editor.offset().left + 'px'
                            ],
                            skin: 'layui-layer-border',
                            content: [
                                '<ul class="layui-form layui-form-pane" style="margin: 20px;">',
                                '<li class="layui-form-item">', '<label class="layui-form-label">URL</label>',
                                '<div class="layui-input-inline">',
                                '<input required name="image" placeholder="支持直接粘贴远程图片地址" value="" class="layui-input">',
                                '</div>',
                                '<button type="button" class="layui-btn layui-btn-primary" id="uploadImg"><i class="layui-icon">&#xe67c;</i>上传图片</button>',
                                '</li>', '<li class="layui-form-item" style="text-align: center;">',
                                '<button type="button" lay-submit lay-filter="uploadImages" class="layui-btn">确认</button>',
                                '</li>', '</ul>'
                            ].join(''),
                            success: function (layero, index) {
                                var image = layero.find('input[name="image"]');

                                //执行上传实例
                                upload.render({
                                    elem: '#uploadImg',
                                    url: '/File/SaveFile?relationGuid=' + options.relationGuid + '&fileTag=' + options.fileTag,
                                    done: function (res) {
                                        if (res.code === 0) {
                                            image.val(res.data);
                                        } else {
                                            layer.msg(res.msg, { icon: 5 });
                                        }
                                    }
                                });

                                form.on('submit(uploadImages)',
                                    function (data) {
                                        var field = data.field;
                                        if (!field.image) return image.focus();
                                        layui.focusInsert(editor[0], 'img[' + field.image + '] ');
                                        layer.close(index);
                                    });
                            }
                        });
                    },

                    //插入链接
                    href: function (editor) {
                        layer.prompt({
                            title: '请输入合法链接',
                            shade: false,
                            fixed: false,
                            id: 'LAY_flyedit_href',
                            offset: [
                                editor.offset().top - $(window).scrollTop() + 'px', editor.offset().left + 'px'
                            ]
                        },
                            function (val, index, elem) {
                                if (!/^http(s*)::\/\/[\S]/.test(val)) {
                                    layer.tips('这根本不是链接', elem, { tips: 1 })
                                    return;
                                }
                                layui.focusInsert(editor[0], ' a(' + val + ')[' + val + '] ');
                                layer.close(index);
                            });
                    },

                    //插入代码
                    code: function (editor) {
                        layer.prompt({
                            title: '请贴入代码或任意文本',
                            formType: 2,
                            maxlength: 10000,
                            shade: false,
                            id: 'LAY_flyedit_code',
                            area: ['800px', '360px']
                        }, function (val, index, elem) {
                            layui.focusInsert(editor[0], '[pre]\n' + val + '\n[/pre]');
                            layer.close(index);
                        });
                    },

                    //插入水平分割线
                    hr: function (editor) {
                        layui.focusInsert(editor[0], '[hr]');
                    },

                    //预览
                    yulan: function (editor) {
                        var content = editor.val();

                        content = /^\{html\}/.test(content)
                            ? content.replace(/^\{html\}/, '')
                            : index.content(content);

                        layer.open({
                            type: 1,
                            title: '预览',
                            shade: false,
                            area: ['100%', '100%'],
                            scrollbar: false,
                            content: '<div class="detail-body" style="margin:20px;">' + content + '</div>'
                        });
                    }
                };

            //表情引入
            layui.extend({
                face: 'lib/face'
            }).use('face', function (face) {
                options = options || {};
                index.faces = face;
                $(options.elem).each(function (index) {
                    var that = this,
                        othis = $(that),
                        parent = othis.parent();
                    parent.prepend(html);
                    parent.find('.fly-edit span').on('click', function (event) {
                        var type = $(this).attr('type');
                        mod[type].call(that, othis, this);
                        if (type === 'face') {
                            event.stopPropagation();
                        }
                    });
                });
            });
        },
        escape: function (html) {
            return String(html || '').replace(/&(?!#?[a-zA-Z0-9]+;)/g, '&amp;')
                .replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/'/g, '&#39;').replace(/"/g, '&quot;');
        },
        content: function (content) {
            //支持的html标签
            var html = function (end) {
                return new RegExp('\\n*\\[' + (end || '') + '(pre|hr|div|span|p|table|thead|th|tbody|tr|td|ul|li|ol|li|dl|dt|dd|h2|h3|h4|h5)([\\s\\S]*?)\\]\\n*', 'g');
            };
            content = index.escape(content || '') //XSS
                .replace(/img\[([^\s]+?)\]/g, function (img) {  //转义图片
                    return '<img src="' + img.replace(/(^img\[)|(\]$)/g, '') + '">';
                })
                .replace(/face\[([^\s\[\]]+?)\]/g, function (face) {  //转义表情
                    var alt = face.replace(/^face/g, '');
                    return '<img alt="' + alt + '" title="' + alt + '" src="' + index.faces[alt] + '">';
                }).replace(/a\([\s\S]+?\)\[[\s\S]*?\]/g, function (str) { //转义链接
                    var href = (str.match(/a\(([\s\S]+?)\)\[/) || [])[1];
                    var text = (str.match(/\)\[([\s\S]*?)\]/) || [])[1];
                    if (!href) return str;
                    var rel = /^(http(s)*:\/\/)\b(?!(\w+\.)*(sentsin.com|layui.com))\b/.test(href.replace(/\s/g, ''));
                    return '<a href="' + href + '" target="_blank"' + (rel ? ' rel="nofollow"' : '') + '>' + (text || href) + '</a>';
                }).replace(html(), '\<$1 $2\>').replace(html('/'), '\</$1\>') //转移HTML代码
                .replace(/\n/g, '<br>') //转义换行   
            return content;
        }


    }

    //固定Bar
    util.fixbar({
        bar1: '&#xe642;',
        bgcolor: '#009688',
        click: function (type) {
            if (type === 'bar1') {
                location.href = '/Post/Publish';
            }
        }
    });
    //自动加载页面所记录的模块
    if (layui.cache.module) {

        //获取内容
        var moduleName = layui.cache.module.moduleName;

        //定义别名对象
        var extend = {};

        //设置别名内容
        extend[moduleName] = 'lib/modules/' + moduleName;
        //加载模块
        layui.extend(extend).use(moduleName);
    }

    //模块对外输出接口
    exports('index', index);
})